import { useState, useRef, useEffect } from 'react';
import { Card, Form, Input, Upload, Button, message } from 'antd';
import {
  CloudUploadOutlined, InboxOutlined, CloudServerOutlined, ExclamationCircleOutlined
} from '@ant-design/icons';
import { useTranslation } from 'react-i18next';

import request from '@/utils/request';

import { updateip, upgrade } from '@/api/config';
import { getState, configState } from '@/api/common';
import './index.scss';

const { Dragger } = Upload;

// 提取常量
const INITIAL_INFO = {
  "ad_serial": "",
  "ipconfig": { "post": "", "ip": "", "cid": "" },
  "cid": "", "ip": "", "post": "", "msg": "",
  "serial_state": "", "state": "", "version": ""
};

function Config() {
  const { t } = useTranslation();
  const uploadRef = useRef();
  const [form] = Form.useForm();
  const [fileList, setFileList] = useState([]);
  const [uploading, setUploading] = useState(false);
  const [status, setStatus] = useState(false);
  const [info, setInfo] = useState(INITIAL_INFO);

  // 提取重复的卡片标题渲染
  const renderCardTitle = (icon, titleKey) => (
    <div className='title'>
      {icon}
      <span className="tit">{t(titleKey)}</span>
    </div>
  );

  const uploadProps = {
    name: 'file',
    multiple: true,
    beforeUpload: (file) => {
      setFileList([...fileList, file]);
      return false;
    },
    onDrop(e) {

    },
    fileList,
    maxCount: 1
  };

  const handleUpload = () => {
    const formData = new FormData();
    if (fileList.length <= 0) {
      return message.error(t("message.selectFile"));
    }
    fileList.forEach((file) => {
      formData.append('file', file);
    });
    setUploading(true);
    request.post('/upload/', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    })
      .then((response) => {
        // axios 返回的数据在 response.data 中
        setFileList([]);
        message.success(t("message.uploadSuccess"));
      })
      .catch((error) => {
        console.error('上传失败:', error);
        message.error(t("message.uploadFailed"));
      })
      .finally(() => {
        setUploading(false);
      });
  };

  function onFinish(values) {
    updateip(values).then(res => {
      message.success(t("message.saveSuccess"))
    })
  }

  function getLoad() {
    getState().then(res => {
      setInfo(res[0]);
    })
    configState().then(res => {
      setStatus(res);
    })
  }

  useEffect(() => {
    getLoad();
  }, [])

  return (
    <div className="config-container">
      <div className="row-a1">
        <div className="left">
          {/* 配置文件上传 */}
          <div className="con-a1">
            <Card title={renderCardTitle(<CloudUploadOutlined style={{ color: '#08c' }} />, "config.configFileUpload")}>
              <div className="upload">
                <Dragger {...uploadProps} ref={uploadRef}>
                  <p className="ant-upload-drag-icon">
                    <InboxOutlined />
                  </p>
                  <p className="ant-upload-text">{t("config.clickOrDrag")}</p>
                  <p className="ant-upload-hint">{t("config.uploadHint")}</p>
                </Dragger>
              </div>
              <Button onClick={handleUpload} type="primary">{t("config.uploadConfigFile")}</Button>
            </Card>
          </div>

          {/* 服务器配置 */}
          <div className="con-a2">
            <Card title={renderCardTitle(<CloudServerOutlined style={{ color: '#08c' }} />, "config.serverConfig")}>
              <Form
                form={form}
                layout="vertical"
                name="form"
                autoComplete="off"
                onFinish={onFinish}
              >
                <Form.Item label={t("config.serverAddress")} name="ip">
                  <Input placeholder={t("config.serverAddressPlaceholder")} />
                </Form.Item>
                <Form.Item label={t("config.shelfNumber")} name="cid">
                  <Input placeholder={t("config.shelfNumberPlaceholder")} />
                </Form.Item>
                <Form.Item>
                  <Button className='submit-btn' type="primary" htmlType="submit">
                    {t("config.saveConfig")}
                  </Button>
                </Form.Item>
              </Form>
            </Card>
          </div>
        </div>

        <div className="right">
          {/* 配置信息 */}
          <div className="con-a3">
            <Card title={renderCardTitle(<ExclamationCircleOutlined style={{ color: '#08c' }} />, "config.configInfo")}>
              <div className="status">
                {t("common.configStatus")}：{(status ? t("common.loadSuccess") : t("common.loadErrorTips"))}
              </div>
              <div className="list">
                <div className="li">
                  <div className="tit">{t("config.serverAddress")}</div>
                  <div className="txt">{info.ipconfig.ip}</div>
                </div>
                <div className="li">
                  <div className="tit">{t("config.shelfNumber")}</div>
                  <div className="txt">{info.ipconfig.cid}</div>
                </div>
                <div className="li">
                  <div className="tit">{t("config.version")}</div>
                  <div className="txt">{info.version}</div>
                </div>
              </div>
            </Card>
          </div>
        </div>
      </div>
    </div>
  )
}

export default Config;